<template>
  <div class="app-container  bg-gray">
    <el-row class="box-1">
      <el-col :span="24">
        <el-card>
          <div class="header">
            <el-button type="success" class="bg-green" icon="el-icon-circle-plus" @click="showRuleDialog()">添加规则</el-button>
            <div>
              <el-input v-model="searchTerms.searchValue" placeholder="请输入内容" class="search-input" @change="getData" />
              <el-button type="success" class="bg-green" icon="el-icon-search" @click="getData">搜索</el-button>
            </div>
          </div>
          <el-table v-loading="tableLoading" :data="tableData" :max-height="tableMaxHeight" border highlight-current-row @sort-change="handleSortChange">
            <el-table-column prop="id" label="ID" width="100" header-align="center" align="center" sortable />
            <el-table-column prop="rule_name" label="规则名称" min-width="200" header-align="center" align="center" />
            <el-table-column prop="rule_type" label="提成类型" min-width="140" header-align="center" align="center">
              <template slot-scope="scope">
                {{ scope.row['type']===1?'售后费用':'奖金' }}
              </template>
            </el-table-column>
            <el-table-column prop="rule_type" label="发放模式" min-width="140" header-align="center" align="center">
              <template slot-scope="scope">
                {{ scope.row['rule_type']===0?'按比例':'固定金额' }}
              </template>
            </el-table-column>
            <el-table-column prop="created_at" label="创建时间" min-width="160" header-align="center" align="center" sortable/>
            <el-table-column prop="rule_type" label="状态" min-width="140" header-align="center" align="center">
              <template slot-scope="scope">
                <div @click="changeStatus(scope['row'])">
                  <el-tag :type="scope['row']['status']?'success':'danger'" class="cursor-p">{{ scope.row['status']?'已启用':'已禁用' }}
                  </el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" header-align="center" align="center">
              <template slot-scope="scope">
                <el-button type="success" size="small" icon="el-icon-edit" circle class="bg-green" @click="showRuleDialog(scope.row)"/>
                <el-button type="danger" size="small" icon="el-icon-delete" circle @click="toDelete(scope.row)" />
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            :current-page.sync="currentPage"
            :page-size="pageSize"
            :page-sizes="pageSizes"
            :total="total"
            class="pagination"
            layout="total, sizes, prev, pager, next, jumper"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"/>
        </el-card>
      </el-col>
    </el-row>

    <el-dialog :visible.sync="dialogVisible" :title="ruleForm.title" width="560px" class="dialog" center @close="ruleForm={}">
      <el-form ref="ruleForm" :model="ruleForm" :rules="ruleFormRules" label-width="150px">
        <el-form-item label="规则名称" prop="rule_name">
          <el-input v-model="ruleForm.rule_name" />
        </el-form-item>
        <el-form-item label="提成类型" prop="rule_type">
          <el-radio-group v-model="ruleForm['type']" :disabled="ruleForm.title==='编辑提成规则'">
            <el-radio :label="0">奖金</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="提成模式" prop="rule_type">
          <el-radio-group v-model="ruleForm['rule_type']" :disabled="ruleForm.title==='编辑提成规则'">
            <el-radio :label="0">按比例</el-radio>
            <el-radio :label="1">固定金额</el-radio>
          </el-radio-group>
          <div class="remark">*注:提成模式保存后不可更改</div>
        </el-form-item>
        <el-form-item v-if="ruleForm['rule_type']===0" label="成本" prop="cost">
          <el-input v-model="ruleForm.cost" type="number">
            <template slot="append">%</template>
          </el-input>
          <div class="remark">*注:成本是按百分比计算</div>
        </el-form-item>
        <el-form-item label="销售业绩提成" prop="pre_bonus">
          <el-input v-model="ruleForm.pre_bonus" type="number">
            <template v-if="!ruleForm['rule_type']" slot="append">%</template>
          </el-input>
        </el-form-item>
        <el-form-item v-if="!ruleForm['type']" label="奖金">
          <el-input v-model="ruleForm['bonus']" type="number">
            <template v-if="!ruleForm['rule_type']" slot="append">%</template>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { handleSortChange, handleSizeChange, handleCurrentChange } from '@/utils/table';
export default {
  data() {
    return {
      searchTerms: {
        searchValue: ''
      },

      dialogVisible: false,
      ruleForm: {
        rule_name: '',
        rule_type: 0,
        type: 0,
        cost: '',
        pre_bonus: '',
        bonus: 0
      },
      ruleFormRules: {
        rule_name: [{ required: true, message: '请输入规则名称', trigger: 'blur' }],
        rule_type: [{ required: true, message: '请选择规则类型', trigger: 'blur' }],
        cost: [{ required: true, message: '请输入成本', trigger: 'blur' }],
        pre_bonus: [{ required: true, message: '请输入销售业绩提成', trigger: 'blur' }]
      },

      // 表格相关数据
      tableMaxHeight: document.documentElement.clientHeight - 280,
      tableLoading: false,
      currentPage: 1,
      pageSize: this.$store.getters.userInfo.pageSize,
      pageSizes: [10, 20, 50, 100, 1000],
      total: 0,
      tableData: []
    }
  },
  watch: {
  },
  created() {
    this.getData();
  },
  methods: {
    handleSortChange, handleSizeChange, handleCurrentChange,
    getData(order) {
      this.tableLoading = true;
      order || (order = {});
      const url = 'salerule/list';
      const data = {
        page_no: this.currentPage,
        page_size: this.pageSize,
        search: this.searchTerms.searchValue
      };
      order.sortName && (data.sortName = order.sortName);
      order.sortOrder && (data.sortOrder = order.sortOrder);
      this.$store.dispatch('GetConnect', { url, data }).then(res => {
        this.tableData = res.data.rows;
        this.total = res.data.total;
        this.tableLoading = false;
      }).catch(e => {
        this.tableLoading = false;
        this.$message.error(e.msg + ',请刷新或联系管理员');
      })
    },

    showRuleDialog(row) {
      row && (this.ruleForm = row);
      // console.log(row)
      this.ruleForm.title = row ? '编辑提成规则' : '创建提成规则';
      this.dialogVisible = true;
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const data = this.ruleForm;
          const url = this.ruleForm.id ? 'salerule/edit/' + this.ruleForm.id : 'salerule/create';
          this.$store.dispatch('GetConnect', { url, data }).then(res => {
            this.$message.success(res.msg);
            this.dialogVisible = false;
            this.getData();
          }).catch((err) => {
            this.$message.error(err.original.msg);
          })
        } else {
          this.$message.error('提交失败,请检查必填项');
        }
      });
    },
    toDelete(row) {
      this.$confirm('此操作将删除该规则, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const url = 'salerule/delete/' + row.id;
        this.$store.dispatch('GetConnect', { url }).then(res => {
          this.$message.success(res.msg);
          this.getData();
        }).catch((err) => {
          this.$message.error(err.msg);
        })
      })
    },
    toModifyRoles(title) {
      this.isShow = false;
      this.$router.push({
        path: '/permissions/roles/modifyRole',
        query: { title: title }
      });
    },

    changeStatus(row){
      this.$confirm('此操作将' + (row.status ? '禁用' : '启用') + '该规则, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const url = 'salerule/updateSaleRule';
        const data = {
          id: row.id,
          status: !row.status
        }
        this.$store.dispatch('GetConnect', { url, data }).then(res => {
          this.$message.success(res.msg);
          this.getData();
        }).catch((err) => {
          this.$message.error(err.msg);
        })
      })
    }
  }
}
</script>

<style lang="scss" type="text/scss" scoped>
@import '../../styles/index.scss';
.box-1 {
  .header {
    @include flex-row(center, space-between);
    padding-bottom: 15px;
    .search-input {
      width: 240px;
    }
  }
}

.dialog {
  .el-input {
    width: 80%;
  }
  .remark {
    font-size: 13px;
    color: $textGray;
  }
}
</style>
